package com.lei.study.depth.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 使用 Curator
 * </p>
 *
 * @author <a href='mailto:17674030991@163.com'/>伍磊
 */
public class CuratorTest {

    public static final String PATH = "/data";

    public static void main(String[] args) throws Exception {
        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 5000, 5000,
                new RetryNTimes(3, 1000));
        client.start();

        // 创建持久节点
        Stat stat = client.checkExists().forPath(PATH);
        if (null == stat) {
            String s = client.create().withMode(CreateMode.PERSISTENT).forPath(PATH, "linshi".getBytes(StandardCharsets.UTF_8));
            System.out.println(s);
        }

        // 创建监听器 监听节点对应增、删、改操作
        NodeCache nodeCache = new NodeCache(client, PATH);
        // 将获取到的值初始化到缓存中，避免一开始就触发事件
        nodeCache.start(true);
        // ExecutorService executorService = Executors.newFixedThreadPool(1);
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("节点变更：" + new String(nodeCache.getCurrentData().getData()));
            }
        });

        // 创建子节点监听器
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, PATH, true);
        // 已存在的子节点不发布事件
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                System.out.println("子节点变化 " + event);
            }
        });

        System.in.read();
    }
}
